package com.ang.juc.n2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 模拟吃饭
 * 5个人，一人一只筷子，获得2只筷子才能吃饭
 * 会死锁
 */
@Slf4j
public class DeadLockTest2 {
    //5根筷子，相当于5个锁
    private static String kz1 = "筷子1";
    private static String kz2 = "筷子2";
    private static String kz3 = "筷子3";
    private static String kz4 = "筷子4";
    private static String kz5 = "筷子5";


    public static void main(String[] args) {
        //5个线程，分别需要2只筷子
        Thread t1 = new Thread(new Person(kz1, kz2),"张三");
        Thread t2 = new Thread(new Person(kz2, kz3),"李四");
        Thread t3 = new Thread(new Person(kz3, kz4),"王五");
        Thread t4 = new Thread(new Person(kz4, kz5),"赵六");
        Thread t5 = new Thread(new Person(kz5, kz1),"孙七");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }

    //公共资源类
    static class Person implements Runnable{
        String kzLeft;
        String kzRight;

        public Person(String kzLeft, String kzRight){
            this.kzLeft = kzLeft;
            this.kzRight = kzRight;
        }

        @Override
        public void run() {
            //吃完休2s，继续吃
            while (true){
                //获取左边筷子
                synchronized (kzLeft){
                    //获取右边筷子
                    synchronized (kzRight){
                        log.debug("{}：获取到2只筷子：{}、{}，开始吃饭", Thread.currentThread().getName(), kzLeft, kzRight);
                    }
                }

                //吃完休息2s
//                try {
//                    Thread.sleep(1);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
            }
        }
    }
}
